{% extends 'base.html' %}
{% load static %}

{% block title %}附近活动 - Meet活动聚{% endblock %}

{% block extra_css %}
<style>
    .form-label {
        position: static !important;
    }
    #nearby-map {
        height: 500px;
        width: 100%;
        border-radius: 8px;
        margin-bottom: 20px;
        border: 1px solid #ddd;
    }

    .radius-selector {
        background: white;
        padding: 15px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .location-status {
        padding: 10px;
        border-radius: 5px;
        margin-bottom: 15px;
    }

    .loading-spinner {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;
        color: #6c757d;
    }

    .map-container {
        position: relative;
    }

    .map-controls {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1000;
        background: white;
        padding: 10px;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h3><i class="bi bi-geo-alt"></i> 附近活动</h3>
                <a href="{% url 'activities:activity_list' %}" class="btn btn-outline-primary">
                    <i class="bi bi-list"></i> 查看所有活动
                </a>
            </div>
        </div>
    </div>

    <!-- 半径选择器 -->
    <div class="radius-selector">
        <div class="row align-items-center">
            <div class="col-md-6">
                <label class="form-label fw-bold" style="margin-top: 5px !important;">搜索半径</label>
                <div class="btn-group" role="group">

                    <input type="radio" class="btn-check" name="radius" id="radius5" value="5" checked>
                    <label class="btn btn-outline-primary" for="radius5">5公里</label>

                    <input type="radio" class="btn-check" name="radius" id="radius10" value="10">
                    <label class="btn btn-outline-primary" for="radius10">10公里</label>

                    <input type="radio" class="btn-check" name="radius" id="radius20" value="20">
                    <label class="btn btn-outline-primary" for="radius20">20公里</label>

                    <input type="radio" class="btn-check" name="radius" id="radius50" value="50">
                    <label class="btn btn-outline-primary" for="radius50">50公里</label>
                </div>
            </div>
            <div class="col-md-6 text-end">
                <button type="button" class="btn btn-success" id="refresh-location">
                    <i class="bi bi-arrow-clockwise"></i> 刷新位置
                </button>
                <button type="button" class="btn btn-primary" id="search-nearby">
                    <i class="bi bi-search"></i> 搜索附近活动
                </button>
            </div>
        </div>
    </div>

    <!-- 位置状态显示 -->
    <div class="location-status alert alert-info" id="location-status">
        <div class="d-flex justify-content-between align-items-center">
            <span id="status-text">正在获取您的位置...</span>
            <span id="coordinates" class="text-muted"></span>
        </div>
    </div>

    <div class="row">
        <!-- 地图区域 -->
        <div class="col-lg-8 mb-4">
            <div class="map-container">
                <div id="nearby-map">
                    <div class="loading-spinner">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载地图...</span>
                        </div>
                        <span class="ms-2">正在加载地图...</span>
                    </div>
                </div>
                <div class="map-controls">
                    <button type="button" class="btn btn-sm btn-outline-primary" id="locate-me">
                        <i class="bi bi-crosshair"></i> 我的位置
                    </button>
                </div>
            </div>
        </div>

        <!-- 活动列表 -->
        <div class="col-lg-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5>附近活动</h5>
                <span class="badge bg-primary" id="activities-count">0 个活动</span>
            </div>
            
            <div id="activities-list">
                <div class="loading-spinner">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <span class="ms-2">等待搜索...</span>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
        <script>
    // 修复谷歌浏览器中汉堡菜单点击问题
document.addEventListener('DOMContentLoaded', function() {
    // 获取所有汉堡菜单按钮
    const hamburgerButtons = document.querySelectorAll('.rd-navbar-project-hamburger');

    // 为每个按钮添加点击事件监听器（确保使用捕获阶段）
    hamburgerButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation();
            e.preventDefault();

            // 手动触发切换效果
            const navbarMain = document.querySelector('.rd-navbar-main');
            navbarMain.classList.toggle('active');

            // 处理背景模糊效果
            const navbarWrap = document.querySelector('.rd-navbar-wrap');
            navbarWrap.classList.toggle('blur');
        }, true); // 使用捕获阶段
    });

    // 修复触摸设备兼容性
    hamburgerButtons.forEach(button => {
        button.addEventListener('touchstart', function(e) {
            e.stopPropagation();
            // 触发点击事件
            this.click();
        }, true);
    });
});
    </script>
<!-- 百度地图API -->
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=8XOhRDI7Z66FkIXDkKu0Gxp9cXxtd2mL"></script>
<script>
    let map = null;
    let userMarker = null;
    let activityMarkers = [];
    let userLocation = null;
    let currentRadius = 5;

    // 初始化地图
    function initMap() {
        try {
            console.log("初始化附近活动地图...");
            
            // 清除加载提示
            document.getElementById('nearby-map').innerHTML = '';
            
            // 初始化百度地图
            map = new BMap.Map("nearby-map");
            
            // 设置默认中心点（河南省郑州市）
            var defaultPoint = new BMap.Point(113.665412, 34.757975);
            map.centerAndZoom(defaultPoint, 12);
            
            // 启用控件
            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());
            map.enableScrollWheelZoom(true);
            
            console.log("地图初始化成功");
            
            // 尝试获取当前位置
            getCurrentLocation();
            
        } catch (error) {
            console.error('地图初始化失败：', error);
            document.getElementById('nearby-map').innerHTML = 
                '<div class="alert alert-danger">地图加载失败：' + error.message + '</div>';
        }
    }

    // 获取当前位置
    async function getCurrentLocation() {
        try {
            updateStatus('正在获取您的位置...', 'info');
            
            const location = await getLocation();
            userLocation = location;
            
            // 更新状态显示
            updateStatus('位置获取成功', 'success');
            document.getElementById('coordinates').textContent = 
                `纬度: ${location.latitude.toFixed(6)}, 经度: ${location.longitude.toFixed(6)}`;
            
            // 在地图上标记用户位置
            markUserLocation(location);
            
            console.log('用户位置获取成功：', location);
            
        } catch (error) {
            console.error('获取位置失败：', error);
            updateStatus('获取位置失败：' + error.message, 'danger');
        }
    }

    // 获取位置（支持GPS和IP定位）
    function getLocation() {
        return new Promise((resolve, reject) => {
            if (!navigator.geolocation) {
                getLocationByIP().then(resolve).catch(reject);
                return;
            }

            const options = {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 60000
            };

            navigator.geolocation.getCurrentPosition(
                function(position) {
                    const location = {
                        latitude: position.coords.latitude,
                        longitude: position.coords.longitude,
                        accuracy: position.coords.accuracy,
                        type: 'gps'
                    };
                    
                    if (isLocationInChina(location.longitude, location.latitude)) {
                        resolve(location);
                    } else {
                        getLocationByIP().then(resolve).catch(reject);
                    }
                },
                function(error) {
                    console.warn('GPS定位失败，尝试IP定位：', error);
                    getLocationByIP().then(resolve).catch(reject);
                },
                options
            );
        });
    }

    // IP定位
    function getLocationByIP() {
        return new Promise((resolve, reject) => {
            var myCity = new BMap.LocalCity();
            myCity.get(function(result) {
                if (result && result.center) {
                    const location = {
                        latitude: result.center.lat,
                        longitude: result.center.lng,
                        accuracy: 5000,
                        type: 'ip',
                        cityName: result.name
                    };
                    resolve(location);
                } else {
                    reject(new Error('IP定位失败'));
                }
            });
        });
    }

    // 检查位置是否在中国
    function isLocationInChina(longitude, latitude) {
        const chinaBounds = {
            minLng: 73.66, maxLng: 135.05,
            minLat: 18.15, maxLat: 53.55
        };
        return longitude >= chinaBounds.minLng && longitude <= chinaBounds.maxLng &&
               latitude >= chinaBounds.minLat && latitude <= chinaBounds.maxLat;
    }

    // 在地图上标记用户位置
    function markUserLocation(location) {
        if (!map) return;
        
        var point = new BMap.Point(location.longitude, location.latitude);
        
        // 移动地图到用户位置
        map.centerAndZoom(point, location.type === 'ip' ? 11 : 14);
        
        // 清除之前的用户标记
        if (userMarker) {
            map.removeOverlay(userMarker);
        }
        
        // 创建用户位置标记
        userMarker = new BMap.Marker(point);
        map.addOverlay(userMarker);
        
        // 添加标签
        var label = new BMap.Label("我的位置", {
            position: point,
            offset: new BMap.Size(15, -30)
        });
        label.setStyle({
            backgroundColor: '#007bff',
            color: 'white',
            padding: '5px 10px',
            border: 'none',
            borderRadius: '12px',
            fontSize: '12px'
        });
        userMarker.setLabel(label);
        
        // 如果是精确位置，添加精度圆圈
        if (location.accuracy && location.type === 'gps') {
            var circle = new BMap.Circle(point, location.accuracy, {
                strokeColor: "#007bff",
                strokeWeight: 2,
                strokeOpacity: 0.5,
                fillColor: "#007bff",
                fillOpacity: 0.1
            });
            map.addOverlay(circle);
        }
    }

    // 搜索附近活动
    async function searchNearbyActivities() {
        if (!userLocation) {
            alert('请先获取您的位置');
            return;
        }

        try {
            updateStatus('正在搜索附近活动...', 'info');
            showLoadingActivities();
            
            const radius = document.querySelector('input[name="radius"]:checked').value;
            currentRadius = parseInt(radius);
            
            // 调用后端API
            const response = await fetch(
                `{% url 'activities:nearby_activities' %}?` + 
                `lat=${userLocation.latitude}&lng=${userLocation.longitude}&radius=${radius}`
            );
            
            const data = await response.json();
            
            if (data.success) {
                displayActivities(data.activities);
                markActivitiesOnMap(data.activities);
                updateStatus(`找到 ${data.activities.length} 个附近活动`, 'success');
            } else {
                throw new Error(data.message || '搜索失败');
            }
            
        } catch (error) {
            console.error('搜索附近活动失败：', error);
            updateStatus('搜索失败：' + error.message, 'danger');
            showNoActivities('搜索失败，请重试');
        }
    }
    // 定义活动详情URL模板
    const ACTIVITY_DETAIL_URL = "{% url 'activities:activity_detail' 0 %}";

    // 辅助函数：生成活动详情URL
    function getActivityDetailUrl(activityId) {
        return ACTIVITY_DETAIL_URL.replace('/0/', `/${activityId}/`);
    }

    // 修改 displayActivities 函数
    function displayActivities(activities) {
        const activitiesList = document.getElementById('activities-list');
        const activitiesCount = document.getElementById('activities-count');

        activitiesCount.textContent = `${activities.length} 个活动`;

        if (activities.length === 0) {
            showNoActivities(`附近 ${currentRadius} 公里内没有找到活动`);
            return;
        }

        let html = '';
        activities.forEach(activity => {
            const detailUrl = getActivityDetailUrl(activity.id);

            html += `
                <div class="card activity-card">
                    <div class="card-body">
                        <div class="position-relative">
                            <span class="badge bg-primary distance-badge">${activity.distance}km</span>
                            <h6 class="card-title">${escapeHtml(activity.title)}</h6>
                        </div>
                        <p class="card-text text-muted small mb-2">
                            <i class="bi bi-geo-alt"></i> ${escapeHtml(activity.location)}
                        </p>
                        <div class="d-flex justify-content-between align-items-center">
                            <a href="${detailUrl}"
                               class="btn btn-sm btn-outline-primary">查看详情</a>
                        </div>
                    </div>
                </div>
            `;
        });

        activitiesList.innerHTML = html;
    }

    // 修改 markActivitiesOnMap 函数
    function markActivitiesOnMap(activities) {
        activityMarkers.forEach(marker => map.removeOverlay(marker));
        activityMarkers = [];

        activities.forEach(activity => {
            var point = new BMap.Point(activity.longitude, activity.latitude);
            var marker = new BMap.Marker(point);
            map.addOverlay(marker);

            const detailUrl = getActivityDetailUrl(activity.id);

            var infoWindow = new BMap.InfoWindow(`
                <div style="max-width: 200px;">
                    <h6>${escapeHtml(activity.title)}</h6>
                    <p class="mb-1"><small>${escapeHtml(activity.location)}</small></p>
                    <p class="mb-1"><small>距离: ${activity.distance}公里</small></p>
                    <a href="${detailUrl}"
                       class="btn btn-sm btn-primary mt-1">查看详情</a>
                </div>
            `);

            marker.addEventListener("click", function() {
                this.openInfoWindow(infoWindow);
            });

            activityMarkers.push(marker);
        });

        if (userLocation && currentRadius) {
            var circle = new BMap.Circle(
                new BMap.Point(userLocation.longitude, userLocation.latitude),
                currentRadius * 1000,
                {
                    strokeColor: "#28a745",
                    strokeWeight: 2,
                    strokeOpacity: 0.8,
                    fillColor: "#28a745",
                    fillOpacity: 0.1
                }
            );
            map.addOverlay(circle);
            activityMarkers.push(circle);
        }
    }
    {#// 显示活动列表#}
    {#function displayActivities(activities) {#}
    {#    const activitiesList = document.getElementById('activities-list');#}
    {#    const activitiesCount = document.getElementById('activities-count');#}
    {#    #}
    {#    activitiesCount.textContent = `${activities.length} 个活动`;#}
    {#    #}
    {#    if (activities.length === 0) {#}
    {#        showNoActivities(`附近 ${currentRadius} 公里内没有找到活动`);#}
    {#        return;#}
    {#    }#}
    {#    #}
    {#    let html = '';#}
    {#    activities.forEach(activity => {#}
    {#        html += `#}
    {#            <div class="card activity-card">#}
    {#                <div class="card-body">#}
    {#                    <div class="position-relative">#}
    {#                        <span class="badge bg-primary distance-badge">${activity.distance}km</span>#}
    {#                        <h6 class="card-title">${escapeHtml(activity.title)}</h6>#}
    {#                    </div>#}
    {#                    <p class="card-text text-muted small mb-2">#}
    {#                        <i class="bi bi-geo-alt"></i> ${escapeHtml(activity.location)}#}
    {#                    </p>#}
    {#                    <div class="d-flex justify-content-between align-items-center">#}
    {#                        <a href="{% url 'activities:activity_detail' 0 %}".replace('0', activity.id) #}
    {#                           class="btn btn-sm btn-outline-primary">查看详情</a>#}
    {#                    </div>#}
    {#                </div>#}
    {#            </div>#}
    {#        `;#}
    {#    });#}
    {#    #}
    {#    activitiesList.innerHTML = html;#}
    {#}#}

    // 在地图上标记活动
    {#function markActivitiesOnMap(activities) {#}
    {#    // 清除之前的活动标记#}
    {#    activityMarkers.forEach(marker => map.removeOverlay(marker));#}
    {#    activityMarkers = [];#}
    {#    #}
    {#    activities.forEach(activity => {#}
    {#        var point = new BMap.Point(activity.longitude, activity.latitude);#}
    {#        #}
    {#        // 创建活动标记#}
    {#        var marker = new BMap.Marker(point);#}
    {#        map.addOverlay(marker);#}
    {#        #}
    {#        // 添加信息窗口#}
    {#        var infoWindow = new BMap.InfoWindow(`#}
    {#            <div style="max-width: 200px;">#}
    {#                <h6>${escapeHtml(activity.title)}</h6>#}
    {#                <p class="mb-1"><small>${escapeHtml(activity.location)}</small></p>#}
    {#                <p class="mb-1"><small>距离: ${activity.distance}公里</small></p>#}
    {#                <a href="{% url 'activities:activity_detail' 0 %}".replace('0', activity.id) #}
    {#                   class="btn btn-sm btn-primary mt-1">查看详情</a>#}
    {#            </div>#}
    {#        `);#}
    {#        #}
    {#        marker.addEventListener("click", function() {#}
    {#            this.openInfoWindow(infoWindow);#}
    {#        });#}
    {#        #}
    {#        activityMarkers.push(marker);#}
    {#    });#}
    {#    #}
    {#    // 添加搜索半径圆圈#}
    {#    if (userLocation && currentRadius) {#}
    {#        var circle = new BMap.Circle(#}
    {#            new BMap.Point(userLocation.longitude, userLocation.latitude),#}
    {#            currentRadius * 1000, // 转换为米#}
    {#            {#}
    {#                strokeColor: "#28a745",#}
    {#                strokeWeight: 2,#}
    {#                strokeOpacity: 0.8,#}
    {#                fillColor: "#28a745",#}
    {#                fillOpacity: 0.1#}
    {#            }#}
    {#        );#}
    {#        map.addOverlay(circle);#}
    {#        activityMarkers.push(circle);#}
    {#    }#}
    {#}#}

    // 显示加载状态
    function showLoadingActivities() {
        document.getElementById('activities-list').innerHTML = `
            <div class="loading-spinner">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <span class="ms-2">搜索中...</span>
            </div>
        `;
    }

    // 显示无活动提示
    function showNoActivities(message) {
        document.getElementById('activities-list').innerHTML = `
            <div class="no-activities">
                <i class="bi bi-inbox" style="font-size: 3rem;"></i>
                <p class="mt-3">${message}</p>
            </div>
        `;
        document.getElementById('activities-count').textContent = '0 个活动';
    }

    // 更新状态显示
    function updateStatus(message, type) {
        const statusElement = document.getElementById('location-status');
        const statusText = document.getElementById('status-text');
        
        statusText.textContent = message;
        statusElement.className = `location-status alert alert-${type}`;
    }

    // HTML转义
    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    // 页面加载完成
    document.addEventListener('DOMContentLoaded', function() {
        console.log('初始化附近活动页面...');
        
        // 初始化地图
        setTimeout(initMap, 100);
        
        // 事件监听
        document.getElementById('search-nearby').addEventListener('click', searchNearbyActivities);
        document.getElementById('refresh-location').addEventListener('click', getCurrentLocation);
        document.getElementById('locate-me').addEventListener('click', getCurrentLocation);
        
        // 半径选择变化时自动搜索
        document.querySelectorAll('input[name="radius"]').forEach(radio => {
            radio.addEventListener('change', function() {
                if (userLocation) {
                    searchNearbyActivities();
                }
            });
        });
        
        // 如果位置已经获取，自动搜索
        setTimeout(() => {
            if (userLocation) {
                searchNearbyActivities();
            }
        }, 2000);
    });
</script>
{% endblock %}